import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

def model_monotony (y_pred, y_true, log_file=None) :
	'''
	模型预测的单调性
	'''
	y_true_pred_reference=pd.DataFrame ( { 'bad_rate': y_pred}) #	^^
	y_true_pred_reference['label'] =y_true.values #  
	bin=[-1,0.1,0.2,0.3,.4,.5,.6,.7,.8,.9,1]
	
	y_true_pred_reference['cut'] =pd.cut(x=y_true_pred_reference['bad_rate'] , bins=bin,labels=np.arange (10) ) 
	sum_true_pred_reference = pd.DataFrame(y_true_pred_reference['cut'].value_counts() ,) #	
	sum_true_pred_reference.columns = ['sample_cnt' ]
	sum_true_pred_reference['real_sum' ] = y_true_pred_reference.groupby('cut')['label'].sum() #	jts&Ml
	sum_true_pred_reference=sum_true_pred_reference.loc [ sum_true_pred_reference[ 'sample_cnt']>0 , : ] 
	sum_true_pred_reference. sort_index(inplace=True)
	sum_true_pred_reference['rate'] = sum_true_pred_reference.apply (lambda row:row	['real_sum']/row['sample_cnt'] , axis=1)
	sum_true_pred_reference[ 'bad_cross' ] =sum_true_pred_reference['rate'].cumsum() # j|?	^
	sum_true_pred_reference[['rate','bad_cross']].plot(figsize=(12,6)) 
	plt.xlabel("model's probability") 
	plt.ylabel("real sample count") 
	plt. title("模型预测的单调性")
	plt. legend(["bad prob",'bad prob_cumulative'])
	if not log_file: 
		plt.show() 
	else:
		plt.savefig(log_file)
		plt.close(0)

def calculate_ks(y_pred , y_true, log_file=None):
	crosstab = pd.crosstab(y_pred,y_true) 
	crossdens = crosstab.cumsum(axis=0)/crosstab.sum() 
	crossdens['gap'] =abs(crossdens[0] - crossdens[1] ) 
	crossdens.columns=['good_prob','bad_prob','KS_line']
	ks_max_row = crossdens[crossdens['KS_line']==crossdens['KS_line'].max()] 
	probability = ks_max_row.index.values[0] 
	plt.figure(figsize=(12,6))
	sns.lineplot(data=crossdens,legend='full') 
	plt.title("KS plot")
	plt.vlines(probability, ymin=0 , ymax=1, colors= 'r' , linestyles= 'dashed' , label='KS_val' ) 
	plt.xlim([0.0,1.0]) 
	plt.ylim([0.0,1.0]) 
	plt.xlabel("model's probability") 
	plt.ylabel("real sample count") 
	plt.legend() 
	if not log_file: 
		plt.show() 
	else :
		plt.savefig(log_file) 
		plt.close(0)
	return ks_max_row['KS_line'].values, probability, crossdens